package test.netty.client;

import fox.framework.rpc.client.message.request.RpcClientRequestAPI;
import fox.framework.rpc.common.WebUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.util.concurrent.TimeUnit;

/**
 * @author cuichao
 * @Description: ClientEncode
 * @Date: create in 2020/12/21 14:58
 */
public class ClientEncode extends MessageToByteEncoder<RpcClientRequestAPI> {
    @Override
    protected void encode(ChannelHandlerContext ctx, RpcClientRequestAPI request, ByteBuf out) throws Exception {




        System.out.println("encode");
        String path = request.getPath();
        String protocol = "fox";
        String body = "test tranfers";
        int contentLength = body.length();
        //parse header
        //first line
        String first = String.format("%s %s\n",protocol,path);
        System.out.println(first +"="+first.getBytes().length);


        out.writeBytes(first.getBytes());


        //second line
        String second = String.format("%s:%s;","request-id",WebUtils.urlEncode("haha:ha"));
        second = second + String.format("%s:%s;\n","contentLength",contentLength);


        out.writeBytes(second.getBytes());

        TimeUnit.SECONDS.sleep(3);


        System.out.println(second +"="+second.getBytes().length);
        //parse body
        String send = first+second+body;
        System.out.println("body:" + body.getBytes().length);


        out.writeBytes(body.getBytes());


        //out.writeBytes(send.getBytes());

    }




   /* @Override
    protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception {
        byte[] bytes = msg.getBytes();
       *//* if(true){
            throw new NullPointerException();
        }*//*
        out.writeInt(bytes.length);
        out.writeBytes(bytes);


    }*/


}
